import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie, Bar, Timeline

# 1. 读取北京2019年天气数据
df = pd.read_csv("./Files/beijing_tianqi_2019.csv")
print(df.head(3))

df['month'] = pd.to_datetime(df['ymd']).dt.month
print(df.head(3))

# 统计每个月份的每种天气出现次数
df_agg = df.groupby(['month', 'tianqi']).size().reset_index()
df_agg.columns = ['month', 'tianqi', 'count']
print(df_agg.head(3))

# 怎样算出1月份的天气次数排名，以下代码是demo，没有实际的逻辑用处
# df_agg['rank'] = df_agg.groupby('month')['count'].rank(ascending=False)
df_agg_new = df_agg[df_agg['month'] == 1][['tianqi', 'count']].sort_values(by='count', ascending=False).values.tolist()
print(df_agg_new)

# 2. 按月变化-天气频率柱状图
timeline = Timeline()
timeline.add_schema(play_interval=1000)
for month in df_agg['month'].unique():
    data = (
        df_agg[df_agg['month'] == month][['tianqi', 'count']]
        .sort_values(by='count', ascending=False)
        .values.tolist()
    )
    # 绘制柱状图
    bar = Bar()
    # X轴是天气名称
    bar.add_xaxis([x[0] for x in data])
    # Y轴是天气出现次数
    bar.add_yaxis('天气出现次数', [x[1] for x in data])
    # 让柱状图横放
    bar.reversal_axis()
    bar.set_global_opts(title_opts=opts.TitleOpts(title='北京每月天气变化'))
    bar.set_series_opts(label_opts=opts.LabelOpts(position='right'))

    timeline.add(bar, "{}月".format(month))

timeline.render('./Files/my_timeline.html')
